#include "ringQueue.hpp"
#include <cstdlib>
#include <ctime>
#include <sys/types.h>
#include <unistd.h>
#include "Task.hpp"

int myAdd(int x, int y)
{
    return x + y;
}

void *consumer(void *args)
{
    RingQueue<Task> *rq = (RingQueue<Task> *)args;
    while (1)
    {
        Task t;
        rq->pop(&t);
        std::cout << pthread_self() << " consumer: " << t.x_ << "+" << t.y_ << "=" << t() << std::endl;
        // sleep(1);
    }
}
void *producer(void *args)
{
    RingQueue<Task> *rq = (RingQueue<Task> *)args;
    while (1)
    {
        // int x = rand() % 100 + 1;
        // std::cout << "生产: " << x << "[" << pthread_self() << "]" << std::endl;
        // rq->push(x);
        int x = rand() % 10 + 1;
        usleep(rand() % 1000);
        int y = rand() % 5 + 1;
        Task t(x, y, myAdd);
        // 生产任务
        rq->push(t);
        // 输出消息
        std::cout << pthread_self() << " productor: " << t.x_ << "+" << t.y_ << "=?" << std::endl;
        sleep(3);
    }
}
int main()
{
    srand((unsigned)time(nullptr) ^ getpid());
    RingQueue<Task> *rq = new RingQueue<Task>();
    pthread_t p, c;
    pthread_create(&c, nullptr, consumer, (void *)rq);
    pthread_create(&p, nullptr, producer, (void *)rq);

    pthread_join(p, nullptr);
    pthread_join(c, nullptr);

    // pthread_t c[3], p[2];
    // pthread_create(c, nullptr, consumer, (void *)rq);
    // pthread_create(c + 1, nullptr, consumer, (void *)rq);
    // pthread_create(c + 2, nullptr, consumer, (void *)rq);
    // pthread_create(p, nullptr, producer, (void *)rq);
    // pthread_create(p + 1, nullptr, producer, (void *)rq);

    // for (int i = 0; i < 3; i++)
    //     pthread_join(c[i], nullptr);
    // for (int i = 0; i < 2; i++)
    //     pthread_join(p[i], nullptr);

    return 0;
}